<script>
import * as echarts from 'echarts'
import dayjs from 'dayjs'

import KCard from '@/components/KCard'

import { debounce } from '@/utils/index'
import { recentVisitor } from '@/api/dashboard'
export default {
  components: {
    KCard
  },
  props: {
    width: {
      default: '100%'
    },
    height: {
      default: '300px'
    }
  },
  data() {
    return {
      loading: false,
      picker: {
        minDate: new Date(),
        maxDate: null
      },
      data: null,
      chart: null,
      chartResizingWithDebounce: debounce(this.chartResizing, 200)
    }
  },
  computed: {
    recentVisitorFormatted() {
      if (this.data === null) return []
      const keys = Object.keys(this.data)
      return keys.map(key => {
        return {
          label: dayjs(key).format('MM-DD'),
          value: this.data[key]
        }
      })
    },
    buildStyles() {
      const { width, height } = this
      return {
        width, height
      }
    },
    pickerOptions() {
      return {
        onPick: (e) => {
          this.picker.minDate = e.minDate
          if (this.picker.minDate && e.maxDate) {
            this.picker.maxDate = e.maxDate
          }
        },
        disabledDate: (e) => {
          if (!(this.picker.minDate instanceof Date)) { return false }

          const minTs = this.picker.minDate.getTime()
          const maxTs = minTs + (24 * 60 * 60 * 1000 * 7)

          return e.getTime() > maxTs || e.getTime() < minTs
        }
      }
    },
    currentRange() {
      // const { minDate, maxDate } = this.picker
      // if (!minDate || !maxDate) { return [new Date(), dayjs().add(7, 'days').toDate()] }

      // return [minDate, maxDate]
      const { minDate } = this.picker
      if(!(minDate instanceof Date))
        return [new Date(), dayjs().add(7, 'days').toDate()]

      return [minDate,dayjs(minDate).add(7,'days').toDate()]
    }
  },
  watch: {
    'currentRange': function() {
      this.$nextTick(() => {
        this.getRecentVisitor()
      })
    },
    recentVisitorFormatted: function(data) {
      if (!Array.isArray(data) || data.length <= 0) return
      console.log(data)
            this.chart?.setOption?.(this.buildOptions())
    }
  },
  created() {
    this.initData()
  },
  mounted() {
    this.chart = echarts.init(document.querySelector('#recent-visitor-chart'))
    window.addEventListener('resize', this.chartResizingWithDebounce)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.chartResizingWithDebounce)
        this.chart?.dispose?.()
  },
  methods: {
    // handlePickerChoose(date) {
      
    //   if (!(date instanceof Date))
    //     date = new Date()
      
    //   this.picker.minDate = date
    //   this.picker.maxDate = dayjs(date).add(7,'days').toDate()
    // },
    chartResizing() {
            this.chart?.resize?.({
              animation: {
                duration: 1500,
                easing: 'elasticOut'
              }
            })
    },
    buildOptions() {
      const xAxis = this.recentVisitorFormatted.map(item => item.label)
      const data = this.recentVisitorFormatted.map(item => item.value)

      const options = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '12%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            name: '(日期)',
            type: 'category',
            data: xAxis,
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        yAxis: [
          {
            name: '(人数)',
            type: 'value'
          }
        ],
        series: [
          {
            name: '人数',
            type: 'bar',
            barWidth: '35%',
            color: '#2F88FF',
            data: data
          }
        ]
      }
      return options
    },
    async getRecentVisitor() {
      try {
        this.loading = true
        const dateRange = this.currentRange
        const params = {
          week: JSON.stringify([
            dayjs(dateRange[0]).format('YYYY-MM-DD'),
            dayjs(dateRange[1]).format('YYYY-MM-DD')
          ])
        }

        const result = await recentVisitor(params)
          .catch(err => {
            throw new Error(err?.response?.data?.message ?? '获取近期访客失败')
          })

        if (result.code !== 200) { throw new Error(result.message ?? '获取近期访客失败') }

        this.data = result.data
        console.log(result, '------result')
        this.loading = false
      } catch (e) {
        this.loading = false
        throw e
      }
    },
    async loadData() {
      await Promise.allSettled([
        this.getRecentVisitor()
      ])
    },
    async initData() {
      await this.loadData()
    }
  }
}
</script>

<template>
  <KCard v-loading="loading" class="recent-visitor" title="近7天访客统计">
    <template #actions>
      <!-- <el-date-picker
        :value="currentRange"
        style="min-width: 188px;max-width: 258px;"
        size="mini"
        type="daterange"
        range-separator="—"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :picker-options="pickerOptions"
        @input="handlePickerChoose"
      /> -->
      <el-date-picker
        type="date"
        size="mini"
        style="width: 130px;"
        placeholder="选择起始日期" 
        v-model="picker.minDate"
      />
    </template>

    <div id="recent-visitor-chart" :style="buildStyles" />
  </KCard>
</template>

<style lang="scss">
.recent-visitor {
    .el-date-editor {
        // width: 100%;
        border: none;
        background-color: #f5f5f5;
        border-radius: 4px;

        .el-input__inner {
            background-color: #f5f5f5;
            color: #8E8E8E;

            &::-webkit-input-placeholder {
                color: #8E8E8E;
            }
        }
    }
}
</style>
